var express=require('express')
var app = require("express")();
var http = require("http").createServer(app);
var io = require("socket.io")(http);
var url= require("url");
var mysql=require("mysql")
var body=require("body-parser")
var file=require("formidable")
var fs=require("fs")
var pa=require("path")
var cookie=require("cookie-parser")
app.use(cookie())
var b=body.urlencoded({extended:false})
app.use("/uploads",express.static("uploads"))
var con=mysql.createConnection({
host:"localhost",
user:"root",
password:"123456",
database:"book"
});
con.connect();
//在使用nodejs里面使用require采用commonjs模块
//在es6里面的js使用impore 通过export或者export default
app.get("/",(req,res)=>{

    console.log(req.cookies.io)
res.sendFile(__dirname + "/index.html");
});
app.post("/user/upload",b,(req,res)=>{
    res.setHeader('Access-Control-Allow-Origin','http://localhost:8080')
    res.setHeader("Access-Control-Allow-Headers","*")
    res.setHeader("Access-Control-Allow-Credentials",'true')
    console.log(req.cookies)
    const f=new file.IncomingForm()
    f.uploadDir="./uploads"
    f.parse(req, function (err, fields, files) {
        if (err) {
            console.log(err)
        } else {
              var oldPath = files.img.path;  //这里的路径是文件的本地路径,但不会显示文件的后缀名
            var fileName=files.img.name    //文件传过来的名字
            console.log(oldPath)
            console.log(fileName)
            var newPath = pa.join(__dirname,'/uploads/'+fileName);   //文件所在位置的绝对路径
            console.log(newPath)
            fs.rename(oldPath, newPath, function () {    //利用fs.rename重命名图片名称
                if(err){
                    res.json({
                        err:"404"
                    })
                }else {
                   res.json({
                       err:"200",
                       url:"http://localhost:4000/uploads/"+files.img.name
                   })
                }
            })
        }
    
    })
})
app.post("/user/details",b,(req,res)=>{
    res.setHeader('Access-Control-Allow-Origin','http://localhost:8080')
    res.setHeader('Access-Control-Allow-Header','*')
    res.setHeader('Access-Control-Allow-Credentials','true')
    res.setHeader('Set-Cookie',"liu=123")
    var form={
        user:req.body.user,
        pass:req.body.pass
    }
    
    res.json(form)
})
app.get("/user/details",(req,res)=>{
     res.setHeader('Access-Control-Allow-Origin','http://localhost:8080')
     res.setHeader('Access-Control-Allow-Headers','*')
     res.setHeader('Access-Control-Allow-Credentials','true')
     console.log(req.cookies)
    res.json({
        user:"liu",
        pass:"0519"
    })
})
io.on("connection",(socket)=> { console.log('123')

socket.emit("dev","hello")
});

//socket.io只能通过http的createserver建立服务器express框架()实例化注入
//http的createserver建立服务器用于监听
//express用于发送请求

http.listen(4000,()=> { console .log('123'); });





